package com.example.elasticsearchdemo;

import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

@RestController
@SpringBootApplication
public class ElasticsearchDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ElasticsearchDemoApplication.class, args);
    }


    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

//    @Autowired
//    private TransportClient client;
//
//    @GetMapping("/people/man/{id}")
//    public Object get(@PathVariable String id){
//        GetResponse response = client.prepareGet("people", "man", id).get();
//        return JSONObject.toJSONString(response);
//    }
//
//    @PostMapping("/people/man/add")
//    public Object add(@RequestParam(name = "name",required = false) String name,@RequestParam(name = "age",required = false,defaultValue = "1") int age ,
//                      @RequestParam(name = "country",required = false) String country,@RequestParam(name = "data",required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date data){
//        try {
//            XContentBuilder content = XContentFactory.jsonBuilder().startObject()
//                    .field("name", name)
//                    .field("age", age)
//                    .field("country", country)
//                    .field("data", data.getTime())
//                    .endObject();
//
//            IndexResponse response = client.prepareIndex("people", "man").setSource(content).get();
//            return JSONObject.toJSONString(response);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return e.getMessage();
//        }
//    }
//
//    @DeleteMapping("/people/man/{id}")
//    public Object add(@PathVariable String id){
//        DeleteResponse response = client.prepareDelete("people", "man", id).get();
//        return JSONObject.toJSONString(response);
//    }
//
//    @PutMapping("/people/man/update")
//    public Object add(@RequestParam String id,@RequestParam String name){
//        UpdateRequest update = new UpdateRequest("people", "man", id);
//        try {
//            XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
//            builder.field("name",name);
//            builder.endObject();
//            update.doc(builder);
//            UpdateResponse response = client.update(update).get();
//            return JSONObject.toJSONString(response);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return e.getMessage();
//        }
//    }
//
//
//
//    @PostMapping("/people/man/query")
//    public Object query(@RequestParam String name){
//        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        boolQuery.must(matchQuery("name",name));
////        boolQuery.filter();
//        SearchRequestBuilder requestBuilder = client.prepareSearch("people").setTypes("man").setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
//                .setQuery(boolQuery).setFrom(0).setSize(1);
//        SearchResponse searchResponse = requestBuilder.get();
//        SearchHits hits = searchResponse.getHits();
//        for (SearchHit hit : hits) {
//            System.out.println("查询结果:"+hit.getSourceAsString());
//        }
//        return JSONObject.toJSONString(searchResponse);
//    }
//
//    @GetMapping("/people/man/list")
//    public Object list(@RequestParam String name){
//        SearchQuery searchQuery = new NativeSearchQueryBuilder()
//                .withQuery(matchQuery("name",name)).build();
//
//        List<Man> resp = elasticsearchTemplate.queryForList(searchQuery, Man.class);
//        return resp;
//    }
////
//    @GetMapping("/people/man/page")
//    public Object page(@RequestParam String name){
//
//        String heightField = "name";
//
//        HighlightBuilder.Field hfield = null;
//        hfield = new HighlightBuilder.Field(heightField).preTags("<mark>").postTags("</mark>");
//        NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder();
//        // 高亮字段
////        nsb.withHighlightFields(hfield);
//        nsb.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));// 评分排序（_source）
//        nsb.withSort(new FieldSortBuilder("age").order(SortOrder.DESC));// 课程排序（courseSort）
//        nsb.withPageable(PageRequest.of(0, 10));
//        // 复合查询，外套boolQuery
//        BoolQueryBuilder qb = QueryBuilders.boolQuery();
//        // 精确查询termQuery不分词，must参数等价于AND
//        qb.must(QueryBuilders.termQuery("name",name));
//        // 模糊查询multiMatchQuery，最佳字段best_fields
////        qb.must(QueryBuilders.multiMatchQuery("country").type(MultiMatchQueryBuilder.Type.BEST_FIELDS));
//
//        nsb.withQuery(qb);
//        NativeSearchQuery nativeSearchQuery = nsb.build();
//        Page<Man> resp = elasticsearchTemplate.queryForPage(nativeSearchQuery, Man.class);
//        return resp;
//    }
//
////    @PostMapping("/people/man/add")
////    public Object add(@RequestBody Map<String,Object> parmas){
////        return null;
////    }
//
//    /**
//     * 分页查询
//     */
//    @GetMapping("/product/page")
//    public Object findPage(@RequestParam(required = false, defaultValue = "1") Integer page,
//                           @RequestParam(required = false, defaultValue = "10") Integer size) {
//        SearchQuery searchQuery = new NativeSearchQueryBuilder()
//                .withQuery(matchAllQuery())
//                .withPageable(
//                        PageRequest.of(page - 1, size, Sort.Direction.ASC, "price"))  //页码是从0 开始
//                .build();
//        return elasticsearchTemplate.queryForList(searchQuery, Product.class);
//    }

}
